package com.example.demo.Impl;

import com.example.demo.entity.MbtiQuestion;
import com.example.demo.entity.Student;
import com.example.demo.entity.TestAnswer;
import com.example.demo.entity.TestRecord;
import com.example.demo.repository.MbtiQuestionRepository;
import com.example.demo.repository.StudentRepository;
import com.example.demo.repository.MbtiAnswerRepository;
import com.example.demo.repository.TestRecordRepository;
import com.example.demo.service.TestAnswerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class TestAnswerServiceImpl implements TestAnswerService {

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private TestRecordRepository testRecordRepository;

    @Autowired
    private MbtiAnswerRepository testAnswerRepository;

    @Autowired
    private MbtiQuestionRepository questionRepository;

    @Override
    public void saveAnswers(SubmitAnswerDTO dto) {
        // 1. 根据学生ID查学生
        Student student = studentRepository.findById(dto.getStudentId())
                .orElseThrow(() -> new RuntimeException("学生不存在"));

        // 2. TODO: 这里可以根据答案计算MBTI类型
        String result = "待实现";

        // 3. 新建测试记录
        TestRecord testRecord = new TestRecord();
        testRecord.setStudent(student);
        testRecord.setTestTime(LocalDateTime.now());
        testRecord.setResult(result);
        testRecord.setResultType("待实现");
        testRecordRepository.save(testRecord);

        // 4. 遍历每题答案，保存
        for (SubmitAnswerDTO.AnswerItem item : dto.getAnswers()) {
            MbtiQuestion question = questionRepository.findById(item.getQuestionId())
                    .orElseThrow(() -> new RuntimeException("题目不存在: " + item.getQuestionId()));

            TestAnswer answer = new TestAnswer();
            answer.setTestRecord(testRecord);
            answer.setQuestion(question);
            answer.setAnswer(item.getAnswer());
            answer.setAnswerTime(LocalDateTime.now());

            testAnswerRepository.save(answer);
        }
    }
}
